from collections import deque
from typing import List


class Solution:
    def longestSubarray(self, nums: List[int], limit: int) -> int:
        ret = 0
        max_q = deque()
        min_q = deque()
        left = 0

        for idx, val in enumerate(nums):
            # 处理队列右侧
            while max_q and val > nums[max_q[-1]]:
                max_q.pop()
            max_q.append(idx)

            while min_q and val < nums[min_q[-1]]:
                min_q.pop()
            min_q.append(idx)

            # 处理队列左侧
            while nums[max_q[0]] - nums[min_q[0]] > limit:
                left += 1
                if max_q[0] < left:
                    max_q.popleft()
                if min_q[0] < left:
                    min_q.popleft()

            # 更新答案
            ret = max(ret, idx - left + 1)
        return ret